package com.cx.mall.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.time.LocalDateTime;

@Configuration
public class MyBatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 配置数据，建议单一数据库类型的均设置 dbType。如果配置多个插件, 切记分页最
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
    /**
     * 创建自动填充配置类实例
     */
    @Bean
    public AutoFieldFillHandler autoFieldFillHandler(){
        return new AutoFieldFillHandler();
    }
    /**
     * 自动填充配置类
     */
    class AutoFieldFillHandler implements MetaObjectHandler {
        @Override
        public void insertFill(MetaObject metaObject) {
            // 自动填充创建时间字段
            strictInsertFill(metaObject,"createTime", LocalDateTime.class,
                    LocalDateTime.now());
            // 自动填充修改时间字段
            strictInsertFill(metaObject,"updateTime", LocalDateTime.class,
                    LocalDateTime.now());
            // 自动填充逻辑删除字段 deleted:0 未删除
            strictInsertFill(metaObject,"deleted",Integer.class,0);
            // 自动填充状态:0 正常
            strictInsertFill(metaObject,"status",Integer.class,0);
         //  strictInsertFill(metaObject,"a",Integer.class,1000);
        }
        @Override
        public void updateFill(MetaObject metaObject) {
            // 自动填充修改时间字段
            strictInsertFill(metaObject,"updateTime", LocalDateTime.class,
                    LocalDateTime.now());
        }
    }
}
